# -*- coding: utf-8 -*-
import poplib, email, telnetlib, smtplib, os, openpyxl, docx, shelve
import datetime, time, sys, traceback, base64
import qian, plan
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr
from apscheduler.schedulers.blocking import BlockingScheduler
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from docxtpl import DocxTemplate

name_list = {
    '李争华': 'lizhenghua@hisense.com',
    '胡高祥': 'hugaoxiang@hisense.com',
    '郑源富': 'zhengyuanfu@hisense.com',
    '周景耀': 'zhoujingyao@hisense.com',
    '甘佐前': 'ganzuoqian@hisense.com',
    '王青': 'wangqing9@hisense.com',
    '罗仕新': 'luoshixin@hisense.com',
    '肖兰': 'xiaolan@hisense.com',
    '黄冠辉': 'huangguanhui@hisense.com',
    '霍佳胜': 'huojiasheng@hisense.com',
    '何伟忠': 'heweizhong@hisense.com',
    '莫海林': 'mohailin@hisense.com',
    '韩国彪': 'hanguobiao@hisense.com',
    '伍志森': 'wuzhisen@hisense.com',
    '郑秋利': 'zhengqiuli@hisense.com',
    '黄永勤': 'huangyongqin@hisense.com',
    '163邮箱':'huang.yongqin@163.com'
}
members = {
    '李争华':{'email':'lizhenghua@hisense.com','tel':'13929193896'},
    '胡高祥':{'email':'hugaoxiang@hisense.com','tel':'18138666862'},
    '郑源富':{'email':'zhengyuanfu@hisense.com','tel':'18128222312'},
    '周景耀':{'email':'zhoujingyao@hisense.com','tel':'18138666355'},
    '甘佐前':{'email':'ganzuoqian@hisense.com','tel':'17762997727'},
    '王青':{'email':'wangqing9@hisense.com','tel':'18138665898'},
    '罗仕新':{'email':'luoshixin@hisense.com','tel':'13715542788'},
    '肖兰':{'email':'xiaolan@hisense.com','tel':'18022995628'},
    '黄冠辉':{'email':'huangguanhui@hisense.com','tel':'18022995138'},
    '霍佳胜':{'email':'huojiasheng@hisense.com','tel':'13715434141'},
    '何伟忠':{'email':'heweizhong@hisense.com','tel':'18138666823'},
    '莫海林':{'email':'mohailin@hisense.com','tel':'18029434436'},
    '韩国彪':{'email':'hanguobiao@hisense.com','tel':'14718443863'},
    '伍志森':{'email':'wuzhisen@hisense.com','tel':'13715546039'},
    '郑秋利':{'email':'zhengqiuli@hisense.com','tel':'18022999258'},
    '黄永勤':{'email':'huangyongqin@hisense.com','tel':'18138666820'}
}
mail_list = [0]
hyq = 'huangyongqin@hisense.com'
liuyouyou = 'liuyouyou1@hisense.com'

class SendMail(object):
    def __init__(self,recv,title,content,username='huang.yongqin@qq.com',passwd='udckfaycpwynbhbi',
                 file=None,ssl=False,
                 email_host='smtp.qq.com',port=25,ssl_port=465):
        '''
        :param username: 用户名
        :param passwd: 密码
        :param recv: 收件人，多个要传list ['a@qq.com','b@qq.com]
        :param title: 邮件标题
        :param content: 邮件正文
        :param file: 附件路径，如果不在当前目录下，要写绝对路径，默认没有附件
        :param ssl: 是否安全链接，默认为普通
        :param email_host: smtp服务器地址，默认为163服务器
        :param port: 非安全链接端口，默认为25
        :param ssl_port: 安全链接端口，默认为465
        '''
        self.username = username #用户名
        self.passwd = passwd #密码
        self.recv = recv #收件人，多个要传list ['a@qq.com','b@qq.com]
        self.title = title #邮件标题
        self.content = content #邮件正文
        self.file = file #附件路径，如果不在当前目录下，要写绝对路径
        self.email_host = email_host #smtp服务器地址
        self.port = port #普通端口
        self.ssl = ssl #是否安全链接
        self.ssl_port = ssl_port #安全链接端口

    def send_mail(self):
        msg = MIMEMultipart()
        #发送内容的对象
        if self.file:#处理附件的
            file_name = os.path.split(self.file)[-1]#只取文件名，不取路径
            try:
                f = open(self.file, 'rb').read()
            except Exception as e:
                raise Exception('附件打不开！！！！')
            else:
                att = MIMEText(f,"base64", "utf-8")
                att["Content-Type"] = 'application/octet-stream'
                #base64.b64encode(file_name.encode()).decode()
                new_file_name='=?utf-8?b?' + base64.b64encode(file_name.encode()).decode() + '?='
                #这里是处理文件名为中文名的，必须这么写
                att["Content-Disposition"] = 'attachment; filename="%s"'%(new_file_name)
                msg.attach(att)
        msg.attach(MIMEText(self.content))#邮件正文的内容
        msg['Subject'] = self.title  # 邮件主题
        msg['From'] = self.username  # 发送者账号
        msg['To'] = ','.join(self.recv)  # 接收者账号列表
        if self.ssl:
            self.smtp = smtplib.SMTP_SSL(self.email_host,port=self.ssl_port)
        else:
            self.smtp = smtplib.SMTP(self.email_host,port=self.port)
        #发送邮件服务器的对象
        self.smtp.login(self.username,self.passwd)
        try:
            self.smtp.sendmail(self.username,self.recv,msg.as_string())
            pass
        except Exception as e:
            print('出错了。。'+str(datetime.datetime.now()),e)
        else:
            print('发送成功！'+str(datetime.datetime.now()))
        self.smtp.quit()


class down_email():
    def __init__(self, user, password, eamil_server):
        # 输入邮件地址, 口令和POP3服务器地址:
        self.user = user
        # 此处密码是授权码,用于登录第三方邮件客户端
        self.password = password
        self.pop3_server = eamil_server
        self.flag = False

    # 获得msg的编码
    def guess_charset(self, msg):
        charset = msg.get_charset()
        if charset is None:
            content_type = msg.get('Content-Type', '').lower()
            pos = content_type.find('charset=')
            if pos >= 0:
                charset = content_type[pos + 8:].strip()
        return charset

    # 获取邮件内容
    def get_content(self, msg):
        content = ''
        content_type = msg.get_content_type()
        # print('content_type:',content_type)
        if content_type == 'text/plain':  # or content_type == 'text/html'
            content = msg.get_payload(decode=True)
            charset = self.guess_charset(msg)
            if charset:
                content = content.decode(charset)
        return content

    # 字符编码转换
    # @staticmethod
    def decode_str(self, str_in):
        value, charset = decode_header(str_in)[0]
        if charset:
            value = value.decode(charset)
        return value

    # 解析邮件,获取附件
    def get_att(self, msg_in,flag = True):
        attachment_files = []
        content = []
        for part in msg_in.walk():
            # 获取附件名称类型
            file_name = part.get_param("name")  # 如果是附件，这里就会取出附件的文件名
            # file_name = part.get_filename() #获取file_name的第2中方法
            # contType = part.get_content_type()
            if file_name:
                h = email.header.Header(file_name)
                # 对附件名称进行解码
                dh = email.header.decode_header(h)
                filename = dh[0][0]
                if dh[0][1]:
                    # 将附件名称可读化
                    filename = self.decode_str(str(filename, dh[0][1]))
                    # print(filename)
                    # filename = filename.encode("utf-8")
                # 下载附件
                data = part.get_payload(decode=True)
                # 在指定目录下创建文件，注意二进制文件需要用wb模式打开
                att_file = open('./附件/' + filename, 'wb')
                att_file.write(data)  # 保存附件
                att_file.close()
                attachment_files.append(filename)
            else:
                # 不是附件，是文本内容
                #print(self.get_content(part))
                content.append(self.get_content(part))
                # # 如果ture的话内容是没用的
                # if not part.is_multipart():
                #     # 解码出文本内容，直接输出来就可以了。
                #     print(part.get_payload(decode=True).decode('utf-8'))
        #print(content)
        if flag:
            return attachment_files
        else:
            return content

    # 获取邮件的信息，包括发件人地址和邮件主题
    def get_info(self, msg):
        From = parseaddr(msg.get('from'))[1]
        subject = self.decode_str(msg.get('Subject'))
        return From, subject

    # 连接POP3邮箱服务器
    def connect_pop(self):
        # 连接到POP3服务器,有些邮箱服务器需要ssl加密，可以使用poplib.POP3_SSL
        try:
            telnetlib.Telnet(self.pop3_server, 995)
            self.server = poplib.POP3_SSL(self.pop3_server, 995, timeout=10)
        except:
            time.sleep(5)
            self.server = poplib.POP3(self.pop3_server, 110, timeout=10)
        # 打印POP3服务器的欢迎文字:
        print(self.server.getwelcome().decode('utf-8'))
        # 身份认证:
        self.server.user(self.user)
        self.server.pass_(self.password)
        self.msg_quantity, self.msg_size = self.server.stat()
        print('Messages: %s. Size: %s' % (self.msg_quantity, self.msg_size))

    # 获取邮件清单
    def get_maillist(self):
        resp, mails, octets = self.server.list()
        return mails

    # 获取邮件msg对象
    def get_msg(self,index):
        # 返回index编号的邮件内容:
        resp, lines, octets = self.server.retr(index)
        # 邮件的原始文本:
        msg_content = b'\r\n'.join(lines).decode('utf-8')
        # 解析邮件:
        msg = Parser().parsestr(msg_content)
        return msg

    def running(self,msg):
        # 返回当日时间:
        str_day = str(datetime.date.today())
        # 获取邮件的发件人，收件人， 抄送人,主题
        From = parseaddr(msg.get('from'))[1]
        To = parseaddr(msg.get('To'))[1]
        Cc = parseaddr(msg.get_all('Cc'))[1]  # 抄送人
        Subject = self.decode_str(msg.get('Subject'))
        print('from:%s,to:%s,Cc:%s,subject:%s' % (From, To, Cc, Subject))
        # 获取附件
        attach_file = self.get_att(msg)
        print('已下载附件：' + str(attach_file))
        return attach_file


def auto(email_class):
    email_class.connect_pop()
    mails = email_class.get_maillist()
    index = len(mails)
    addr_list = []
    db = shelve.open('mails')
    old_list = db['mail']
    try:
        quantity = db['quantity']
        if quantity != email_class.msg_quantity:
            flag = True
        else:
            flag = False
            print('没有新邮件。。。')
    except:
        quantity = email_class.msg_quantity
        db['quantity'] = quantity
        flag = False
    if flag:
        print('好像有变化了~~')
        for i in range(index, index - 10, -1):
            msg = email_class.get_msg(i)
            from_addr, subject = email_class.get_info(msg)
            content = email_class.get_att(msg, False)
            #print(from_addr, subject)
            num_obj = Number()
            filename = None
            if [from_addr, subject, content] not in old_list:
                print('有新邮件。。。。')
                print(str(i), [from_addr, subject])
                if from_addr in name_list.values():
                    if '招标公告' in subject:
                        addr_list.append(from_addr)
                        #下载邮件附件，并取得附件的清单
                        files = email_class.running(msg)
                        #取得公告编号
                        number = num_obj.getNumber()
                        time.sleep(1)
                        #生成Notice公告类，初始化字典，替代模板
                        gg = Notice(files,number)
                        #取得项目名称title和项目负责人name
                        title = gg.title
                        name = gg.name
                        #取得已生成的项目字典
                        title_dict = num_obj.getDict()
                        #比较是否已生成过
                        if num_obj.compare(name, title, title_dict):
                            print('已重复生成')
                            mail_title = '自动生成错误，重复生成'
                            mail_content = ('经过查找，本项目名称:"%s"已经生成过一次招标公告，请排查是否重复' % title)
                            send(addr_list, mail_title, mail_content)
                        else:
                            #取得已完成的公告附件文件名及路径
                            filename = gg.getfile()
                            mail_title = '自动生成招标公告，请见附件'
                            mail_content = ('已收到您的邮件,已生成"%s"招标公告，请见附件' % title)
                            addr_list.append(hyq)
                            addr_list.append(liuyouyou)
                            send(addr_list, mail_title, mail_content, filename=filename)
                            num_obj.insert_number(name, title, number)
                    elif '编号' in subject:
                        addr_list.append(from_addr)
                        content = email_class.get_att(msg,False)
                        text = format_content(content)
                        print('需要编号的内容是：' + text)
                        #取得公告编号
                        number = num_obj.getNumber()
                        #取得已生成的项目字典
                        title_dict = num_obj.getDict()
                        if num_obj.compare(getKey(name_list, from_addr), text, title_dict):
                            print('公告名称已重复生成')
                            mail_title = '自动生成错误，重复生成'
                            mail_content = ('经过查找，本公告名称:"%s" 已申请过一次编号，请排查是否重复' % text)
                            send(addr_list, mail_title, mail_content)
                        else:
                            mail_title = '自动生成公告编号'
                            mail_content = '申请的公告名称:' + text + '\n公告编号：' + str(number)
                            addr_list.append(hyq)
                            send(addr_list, mail_title, mail_content)
                            num_obj.insert_number(getKey(name_list, from_addr), text, number)
                    elif '合同' in subject:
                        addr_list.append(from_addr)
                        #下载邮件附件，并取得附件的清单
                        files = email_class.running(msg)
                        if '工程合同' in files[0]:
                            temp = '工程合同模板.docx'
                            file = '工程合同.docx'
                            table_flag = False
                        else:
                            temp = '采购合同模板.docx'
                            file = '采购合同.docx'
                            table_flag = True
                        num_obj = Number(flag=2)
                        #取得合同编号
                        contract_num = num_obj.getNumber()
                        print('合同编号：%s' % contract_num)
                        time.sleep(1)
                        #生成Notice公告类，初始化字典，替代模板
                        contract_obj = Contract(files, contract_num, table_flag)
                        #取得项目名称title和项目负责人name
                        title = contract_obj.title
                        name = contract_obj.name
                        #取得已生成的项目字典
                        title_dict = num_obj.getDict()
                        if num_obj.compare(name, title, title_dict):
                            print('已重复生成')
                            mail_title = '自动生成错误，重复生成'
                            mail_content = ('经过查找，本项目名称:"%s"已经生成过一次合同，请排查是否重复' % title)
                            send(addr_list, mail_title, mail_content)
                        else:
                            #取得已完成的合同附件文件名及路径
                            org_filename = contract_obj.getfile(temp, file)
                            filename = contract_obj.insert_table(org_filename, table_flag)
                            mail_title = '自动生成合同，请见附件'
                            mail_content = ('已收到您的邮件,已生成"%s"合同，请见附件' % title)
                            addr_list.append(hyq)
                            send(addr_list, mail_title, mail_content, filename=filename)
                            num_obj.insert_number(name, title, contract_num, company=contract_obj.content['company'], total=contract_obj.content['total'])
                old_list.append([from_addr, subject, content])
                db['mail'] = old_list
        db['quantity'] = email_class.msg_quantity
    db.close()
    email_class.server.quit()


def getKey(dic,value):
    keys = filter(lambda x: value == x[1], dic.items())
    for (key,value) in keys:
        return key


def format_content(content):
    for text in content:
        if isinstance(text, str) and text != '':
            break
    text = text.strip()
    print(text)
    texts = text.split('\n')
    print(texts)
    return texts[0]


def send(addr_list, mail_title, mail_content, filename=None):
    while True:
        try:
            m = SendMail(recv=addr_list, title=mail_title, file=filename, content=mail_content,
                         ssl=True, )
            m.send_mail()
            break
        except:
            time.sleep(20)


# 公告
class Notice(object):
    def __init__(self, files, number):
        self.content = {}
        self.files = files
        self.number = number
        self.content.setdefault('number', self.number)
        self.content.setdefault('today', datetime.datetime.today().strftime('%Y-%m-%d'))
        self.copy()

    def copy(self):
        try:
            for file in self.files:
                filename = os.path.join('./附件/', file)
                print(filename)
                wb = openpyxl.load_workbook(filename,data_only=True)
                sheet = wb.active
                self.content.setdefault('title',sheet.cell(row=3,column=1).value)
                self.content.setdefault('name',sheet.cell(row=3,column=2).value)
                self.title = self.content['title']
                self.name = self.content['name']
                self.content.setdefault('teding',sheet.cell(row=3,column=3).value)
                deadline = sheet.cell(row=3,column=4).value
                deadline_date = str(deadline.year) + '年' + str(deadline.month) + '月' + str(deadline.day) + '日'
                self.content.setdefault('deadline',deadline_date)
                _open = sheet.cell(row=3,column=5).value
                open_date = str(_open.year) + '年' + str(_open.month) + '月' + str(_open.day) + '日'
                self.content.setdefault('open_date',open_date)
                self.content.setdefault('money',sheet.cell(row=3,column=6).value)
                self.content.setdefault('tec_context',sheet.cell(row=3,column=7).value)
                self.content.setdefault('money2', qian.verbose_price(int(sheet.cell(row=3,column=6).value)))
                self.content.setdefault('email',members[sheet.cell(row=3,column=2).value]['email'])
                self.content.setdefault('tel',members[sheet.cell(row=3,column=2).value]['tel'])
                if '现场' in sheet.cell(row=3, column=8).value:
                    self.content.setdefault('way', '现场开评标，投标人携带第一标标书至开标现场')
                else:
                    self.content.setdefault('way', '网络开评标，在投标截止时间前，投标人将标书送到项目负责人手上')
                if isinstance(self.content['deadline'],int):
                    self.content['deadline'] = date(self.content['deadline'])
                if isinstance(self.content['open_date'], int):
                    self.content['open_date'] = date(self.content['open_date'])
                print(self.content)
                self.ok = True
        except:
            print('附件有错')
            #os.remove(filename)
            self.ok = False

    def getfile(self, temp='招标公告模板.docx', file='招标公告.docx'):
        if self.ok is True:
            filename = os.path.join('./模板/', temp)
            document = DocxTemplate(filename)
            document.render(self.content)
            filename = os.path.join('./ok/', file)
            document.save(filename)
            return filename
        else:
            return False


class Contract(Notice):
    def __init__(self, files, number, flag):
        self.flag = flag
        super().__init__(files, number)

    #采购合同，则flag==True
    def copy(self):
        try:
            for file in self.files:
                filename = os.path.join('./附件/', file)
                wb = openpyxl.load_workbook(filename, data_only=True)
                self.sheet = wb.active
                if self.flag:
                    key_list = ['title', 'name', 'company', 'legal_person', 'company_adr', 'total', 'tax', 'ftimes',
                            'dilivery_cycle', 'dilivery_addr', 'accept_time', 'accept_method', 'period', 'deposit',
                            'validity', 'much']
                else:
                    key_list = ['title', 'name', 'company', 'legal_person', 'company_adr', 'addr', 'total', 'tax', 'who',
                                'ftimes', 'dilivery_cycle', 'period', 'much']
                for index, key in zip(range(1,len(key_list)+1), key_list):
                    self.content.setdefault(key, self.sheet.cell(row=index, column=2).value)
                if isinstance(self.content['dilivery_cycle'], int):
                    self.content['dilivery_cycle'] = date(self.content['dilivery_cycle'])
                self.title, self.name = self.content['title'], self.content['name']
                self.content['tax'] = str(int(self.content['tax'] * 100)) + '%'
                self.content.setdefault('total2', qian.verbose_price(self.content['total']))
                self.content.setdefault('email', members[self.name]['email'])
                self.content.setdefault('tel', members[self.name]['tel'])
                if self.flag:
                    self.content.setdefault('quantity', self.sheet['H7'].value)
                    if '交货' in self.content['accept_time'] or '交付' in self.content['accept_time']:
                        print(self.content['accept_time'])
                        continue
                    else:
                        accept = '乙方完成安装调试且试运行合格，工作成果经生产试用' + self.content['accept_time'] + '，书面通知甲方验收。'
                        self.content['accept_time'] = accept
                    print(self.content)
                self.ok = True
        except Exception as e:
            print('附件有错')
            print(e)
            os.remove(filename)
            self.ok = False
        self.insert_dilivery()

    def insert_table(self, org_filename, flag):
        if flag:
            doc = docx.Document(org_filename)
            table = doc.tables[0]
            for row in range(3, 7):
                if self.sheet.cell(row=row, column=5).value is None:
                    table.rows[row - 2].cells[1].text = '以下空白'
                    break
                for column in range(4, 11):
                    table.rows[row - 2].cells[column - 4].text = str(self.sheet.cell(row=row, column=column).value)
            doc.save(org_filename)
        return org_filename

    #插入交付条款
    def insert_dilivery(self):
        percent = [0,0,0,0]
        percent[0], money1, condition1 = self.sheet['E9'].value, self.sheet['F9'].value, \
                                       self.sheet['G9'].value
        percent[1], money2, condition2 = self.sheet['E10'].value, self.sheet['F10'].value, \
                                       self.sheet['G10'].value
        percent[2], money3, condition3 = self.sheet['E11'].value, self.sheet['F11'].value, \
                                       self.sheet['G11'].value
        percent[3], money4, condition4 = self.sheet['E12'].value, self.sheet['F12'].value, \
                                       self.sheet['G12'].value
        for i in range(4):
            if percent[i] is None:
                continue
            else:
                percent[i] = str(int(percent[i] * 100)) + '%'
        if self.flag:
            if '4次' in self.content['ftimes']:
                no1 = '1、' + condition1 + '，付合同总金额' + percent[0] + '款项作为订金，实付人民币' + qian.verbose_price(money1) +\
                      '（大写），即¥' + str(money1) + '元（小写）；'
                no2 = '2、' + condition2 + '，第二次付合同总金额款项' + percent[1] + '，实付人民币' + qian.verbose_price(money2) + \
                      '（大写），即¥' + str(money2) + '元（小写）；'
                no3 = '3、' + condition3 + '支付合同结算价款的' + percent[2] + '，实付人民币' + qian.verbose_price(money3) + \
                      '（大写），即¥' + str(money3) + '元（小写）；'
                no4 = '4、本合同总款项的' + percent[3] + '，实付人民币' + qian.verbose_price(money4) + \
                      '（大写），即¥' + str(money4) + '元（小写）,作为乙方履行本合同的质量保证金。' + condition4
                self.content.setdefault('no1', no1)
                self.content.setdefault('no2', no2)
                self.content.setdefault('no3', no3)
                self.content.setdefault('no4', no4)
            elif '3次' in self.content['ftimes']:
                no1 = '1、' + condition1 + '，付合同总金额' + percent[0] + '款项作为订金，实付人民币' + qian.verbose_price(money1) + \
                      '（大写），即¥' + str(money1) + '元（小写）；'
                no2 = '2、' + condition2 + '，第二次付合同总金额款项' + percent[1] + '，实付人民币' + qian.verbose_price(money2) + \
                      '（大写），即¥' + str(money2) + '元（小写）；'
                no3 = '3、本合同总款项的' + percent[2] + '，实付人民币' + qian.verbose_price(money3) + \
                      '（大写），即¥' + str(money3) + '元（小写）,作为乙方履行本合同的质量保证金。' + condition3 + '。'
                self.content.setdefault('no1', no1)
                self.content.setdefault('no2', no2)
                self.content.setdefault('no3', no3)
            elif '2次' in self.content['ftimes']:
                no1 = '1、' + condition1 + '，付合同总金额' + percent[0] + '款项作为订金，实付人民币' + qian.verbose_price(money1) + \
                      '（大写），即¥' + str(money1) + '元（小写）；'
                no2 = '2、' + condition2 + '支付合同结算价款的' + percent[1] + '，实付人民币' + qian.verbose_price(money2) + \
                      '（大写），即¥' + str(money2) + '元（小写）。'
                self.content.setdefault('no1', no1)
                self.content.setdefault('no2', no2)
            elif '一次' in self.content['ftimes']:
                no1 = condition1 + '一次性支付人民币：'+ qian.verbose_price(money1) + \
                      '（大写），即¥' + str(money1) + '元（小写）。'
                self.content.setdefault('no1', no1)
        else:
            if '4次' in self.content['ftimes']:
                no1 = '（1）' + condition1 + '甲方支付合同结算价款的' + percent[0] + '作为预付款，即人民币' + qian.verbose_price(money1) +\
                      '（大写），即¥' + str(money1) + '元（小写）；'
                no2 = '（2）' + condition2 + '支付合同结算价款的' + percent[1] + '，即人民币' + qian.verbose_price(money2) + \
                      '（大写），即¥' + str(money2) + '元（小写）；'
                no3 = '（3）' + condition3 + '支付合同结算价款的' + percent[2] + '，即人民币' + qian.verbose_price(money3) + \
                      '（大写），即¥' + str(money3) + '元（小写）；'
                no4 = '（4）合同结算价款的' + percent[3] + '作为质量保证金，' + condition4 + '，即人民币' + qian.verbose_price(money4) + \
                      '（大写），即¥' + str(money4) + '元（小写）。'
                self.content.setdefault('no1', no1)
                self.content.setdefault('no2', no2)
                self.content.setdefault('no3', no3)
                self.content.setdefault('no4', no4)
            elif '3次' in self.content['ftimes']:
                no1 = '1、' + condition1 + '甲方支付合同结算价款的' + percent[0] + '作为预付款，即人民币' + qian.verbose_price(money1) +\
                      '（大写），即¥' + str(money1) + '元（小写）；'
                no2 = '2、' + condition2 + '支付合同结算价款的' + percent[1] + '，即人民币' + qian.verbose_price(money2) + \
                      '（大写），即¥' + str(money2) + '元（小写）；'
                no3 = '3、合同结算价款的' + percent[2] + '作为质量保证金，' + condition3 + '，即人民币' + qian.verbose_price(money3) + \
                      '（大写），即¥' + str(money3) + '元（小写）。'
                self.content.setdefault('no1', no1)
                self.content.setdefault('no2', no2)
                self.content.setdefault('no3', no3)
        print(self.content)


# 定义转化日期戳的函数,dates为日期戳
def date(dates):
    delta=datetime.timedelta(days=dates)
    # 将1899-12-30转化为可以计算的时间格式并加上要转化的日期戳
    today=datetime.datetime.strptime('1899-12-30','%Y-%m-%d')+delta
    # 制定输出日期的格式
    return datetime.datetime.strftime(today,'%Y-%m-%d')


class Number(object):
    def __init__(self, flag=1):
        '''
        :param flag: 数值为1时，选择公告明细，数值为2时，选择技改项目明细
        '''
        self.flag = flag
        if self.flag == 1:
            self.filename = os.path.join('./模板/', '公告编号明细.xlsx')
        elif self.flag == 2:
            self.filename = os.path.join('./模板/', '技改项目明细.xlsx')
        self.wb = openpyxl.load_workbook(self.filename, data_only=True)
        self.sheet = self.wb.active

    def getNumber(self):
        for i in range(1, self.sheet.max_row+2):
            if self.sheet.cell(row=i, column=1).value is None:
                print('第%s是空白的。' % i)
                break
        if self.flag == 1:
            number = self.sheet.cell(row=i-1, column=1).value
            return number + 1
        elif self.flag == 2:
            value = self.sheet.cell(row=i-1, column=1).value
            value = value.split('-')
            number = int(value[-1])+1
            contract_num = value[0] + '-' + value[1] + '-' + str(number)
            return contract_num

    def getDict(self):
        dict = {}
        for i in range(3,self.sheet.max_row+2):
            key = self.sheet.cell(row=i,column=2).value
            value = self.sheet.cell(row=i,column=3).value
            dict.setdefault(key,value)
            if key is None:
                break
        return dict

    def compare(self, name, title, dict):
        if dict.get(title) == name:
            return True
        else:
            return False

    def insert_number(self,name,title,number,company=None,total=None):
        if self.flag == 1:
            for i in range(3, self.sheet.max_row + 2):
                key = self.sheet.cell(row=i, column=2).value
                if key is None:
                    break
            self.sheet.cell(row=i, column=1).value = number
            self.sheet.cell(row=i, column=2).value = title
            self.sheet.cell(row=i, column=3).value = name
            self.sheet.cell(row=i, column=4).value = datetime.datetime.today().strftime('%Y-%m-%d')
            self.wb.save(self.filename)
        elif self.flag == 2:
            for i in range(3, self.sheet.max_row + 2):
                key = self.sheet.cell(row=i, column=2).value
                if key is None:
                    break
            self.sheet.cell(row=i, column=1).value = number
            self.sheet.cell(row=i, column=2).value = title
            self.sheet.cell(row=i, column=3).value = name
            self.sheet.cell(row=i, column=4).value = company
            self.sheet.cell(row=i, column=5).value = total
            self.sheet.cell(row=i, column=6).value = datetime.datetime.today().strftime('%Y-%m-%d')
            self.wb.save(self.filename)



if __name__ == '__main__':
    # 把打印内容输出到文件
    # origin = sys.stdout
    # f = open('./test/log.txt', 'w')
    # sys.stdout = f
    scheduler = BlockingScheduler()
    try:
        # 输入邮件地址, 口令和POP3服务器地址:
        user = 'huang.yongqin@qq.com'
        # 此处密码是授权码,用于登录第三方邮件客户端
        password = 'udckfaycpwynbhbi'
        eamil_server = 'pop.qq.com'
        email_class = down_email(user=user, password=password, eamil_server=eamil_server)
        #每个20秒执行一次文档自动生成程序，收到邮件需求则自动生成招标公告、采购合同、工程合同及申请编号
        scheduler.add_job(auto, 'interval', seconds=20, args=[email_class])
        #每周五早上9点执行一次提醒程序，提醒每个工程点检本周工作计划和提交下周工作计划
        scheduler.add_job(plan.remind_plan, 'cron', day_of_week='fri', hour=9, args=[name_list])
        scheduler.start()
    except Exception as e:
        import traceback
        ex_msg = '{exception}'.format(exception=traceback.format_exc())
        print(ex_msg)
        # traceback.print_exc()
        # sys.stdout = origin
        # f.close()
    finally:
        email_class.server.quit()
